//
//  MHLoginViewController.m
//  MHO
//
//  Created by papo on 2/24/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "MHUserInfoViewController.h"
#import "MHNavibarView.h"
#import "UserInfoCell.h"
#import "MHAppDelegate.h"
#import "Lib.h"
#import "MHChangePassViewController.h"
#import "ActionSheetStringPicker.h"
#import "MHHistoryListViewController.h"

#define kCardName @"cardName"
#define kCardId @"cardId"

@interface MHUserInfoViewController () <UITextFieldDelegate, UIGestureRecognizerDelegate>
{
    NSArray* titleArray;
    NSArray* iconArray;
    NSInteger   userTK0, userTK1, userTK2;
    CGSize keyboardSize;
}
@property (nonatomic, strong) IBOutlet UIView* addCoinView;
@property (nonatomic, strong) IBOutlet UIView* sendCoinView;
@property (nonatomic, weak) IBOutlet UITextField* cardType;
@property (nonatomic, weak) IBOutlet UITextField* cardNumber;
@property (nonatomic, weak) IBOutlet UITextField* cardSerial;
@property (nonatomic, strong) ActionSheetStringPicker* cardActionSheet;

@property (nonatomic, weak) IBOutlet UITextField* receiveEmail;
@property (nonatomic, weak) IBOutlet UITextField* sendMoney;
@property (nonatomic, weak) IBOutlet UITextField* sendTotalMoney;


@property (nonatomic, strong) NSArray* cardData;
@property (nonatomic, assign) NSInteger cardIndex;
@property (nonatomic, weak) UITextField*    currentTextfield;

@property (nonatomic, assign) int sendFee;

@end

@implementation MHUserInfoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    titleArray = @[@[@"TK chính: %d Gold", @"TK KM1: %d Gold", @"TK KM2: %d Gold"], @[@"Số dư tài khoản", @"Nạp tiền", @"Chuyển tiền", @"Lịch sử giao dịch", @"Thông tin tài khoản"], @[@"Thông tin ứng dụng", @"Thay đổi mật khẩu"]];
    iconArray = @[@[@"icon_tk_chinh.png", @"icon_tk_chinh.png", @"icon_tk_chinh.png"], @[@"icon_so_du_tk.png", @"icon_nap_tien.png", @"icon_chuyen_tien.png", @"icon_lich_su_giao_dich.png", @"icon_thong_tin_tk.png"], @[@"icon_thong_tin_ung_dung.png", @"icon_thay_doi_mk.png"]];
    
    self.cardData = @[ @{
                           kCardName: @"Vina",
                           kCardId : @"1"
                           },
                       @{
                           kCardName: @"Mobile",
                           kCardId: @"2"
                           },
                       @{
                           kCardName: @"Viettel",
                           kCardId: @"3"
                           },
                       @{
                           kCardName: @"Vcoin",
                           kCardId: @"5"
                           },
                       @{
                           kCardName: @"Zing",
                           kCardId: @"6"
                           }
                      ];
    self.cardIndex = 0;
    
    self.addCoinView.layer.cornerRadius = 10;
    self.addCoinView.layer.borderColor = [[UIColor grayColor] CGColor];
    self.addCoinView.layer.borderWidth = 2;
    
    
    self.sendCoinView.layer.cornerRadius = 10;
    self.sendCoinView.layer.borderColor = [[UIColor grayColor] CGColor];
    self.sendCoinView.layer.borderWidth = 2;
    
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];
    self.sendFee = -1;
    
    [self registerForKeyboardNotifications];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self reloadData];
}

- (void)tapGesture: (UIGestureRecognizer*)gesture {
    [self.addCoinView endEditing:YES];
    [self.sendCoinView endEditing:YES];
}

#pragma mark UIGestureRecognizerDelegate methods

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    
    if ([touch.view isDescendantOfView:self.tableView] && self.addCoinView.superview == nil && self.sendCoinView.superview == nil) {
        
        // Don't let selections of auto-complete entries fire the
        // gesture recognizer
        return NO;
    }
    
    return YES;
}

- (void)reloadData {
    static NSInteger serverID = 4;
    static NSString* tk = @"b631241a-5905-471e-95dd-0349a7b8f388";
    NSString* email = [Lib stringForKey:@"Email"];
    NSString* token = [Lib md5:[NSString stringWithFormat:@"%@%ld%@", email, (long)serverID, tk]];
    NSString* url = [NSString stringWithFormat:@"http://paygate.mho.vn/AccountInfo/GetInfo?userEmail=%@&serviceId=%ld&token=%@", email, (long)serverID, token];
    
    [Lib showLoadingView];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString* retVal = [ServiceLib sendGetRequest:url];
        if (retVal) {
            SBJsonParser* parser = [[SBJsonParser alloc] init];
            NSDictionary* dict = [parser objectWithString:retVal];
            if (dict) {
                userTK0 = [numberCheckNull([dict objectForKey:@"TK1"] ) integerValue];
                userTK1 = [numberCheckNull([dict objectForKey:@"TK2"] ) integerValue];
                userTK2 = [numberCheckNull([dict objectForKey:@"TK3"] ) integerValue];
            }
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [Lib removeLoadingView];
            [self.tableView reloadData];
        });
    });
}


#pragma mark - TableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    return [titleArray[section - 1] count];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        if (indexPath.section == 0) {
            cell = [[UITableViewCell alloc] init];//WithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            [cell.contentView addSubview:self.topUserView];
        }
        else {
            cell = [UserInfoCell cellFromNib];
            if (indexPath.section > 1) {
                [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
            }
        }
        UIView* bgView = [[UIView alloc] init];
        bgView.backgroundColor = [UIColor blackColor];
        [cell setSelectedBackgroundView:bgView];
    }
    
    //
    if (indexPath.section > 0) {
        UserInfoCell* uCell = (UserInfoCell*)cell;
        
        if (uCell && [uCell isKindOfClass:[UserInfoCell class]]) {
            uCell.icon.image = [UIImage imageNamed:[iconArray[indexPath.section - 1] objectAtIndex:indexPath.row]] ;
            if (indexPath.section == 1) {
                NSInteger gold = 0;
                if (indexPath.row == 0) {
                    gold = userTK0;
                }
                else if (indexPath.row == 1) {
                    gold = userTK1;
                }
                else {
                    gold = userTK2;
                }
                
                uCell.label.text = [NSString stringWithFormat:[titleArray[indexPath.section - 1] objectAtIndex:indexPath.row], gold];
            }
            else {
                uCell.label.text = [titleArray[indexPath.section - 1] objectAtIndex:indexPath.row];
            }
        }
        else {
            
        }
    }
    else {
        self.userName.text = [Lib stringForKey:kAccountPublicName];
        self.userPhone.text = [Lib stringForKey:@"Phone"];
        [self.userAvatar setImageWithURL:[Contants getImageUrl:[Lib stringForKey:@"Avatar"] width:100 height:100]];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 100;
    }
    return 44;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 2;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView* view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"View"];
    if (!view) {
        view = [[UIView alloc] init];
        view.backgroundColor = [UIColor blackColor];
    }
    return view;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if ([self.addCoinView superview] || [self.sendCoinView superview]) {
        [self.addCoinView endEditing:YES];
        [self.sendCoinView endEditing:YES];
        return;
    }
    if (indexPath.section == 2) {
        if (indexPath.row == 1) {
            CGRect frame1 = self.view.frame;
            CGRect frame2 = self.addCoinView.frame;
            CGRect frame = CGRectMake((frame1.size.width - frame2.size.width) / 2, (frame1.size.height - frame2.size.height) / 2, frame2.size.width, frame2.size.height);
            self.addCoinView.frame = frame;
            [self.view addSubview:self.addCoinView];
        }
        else if (indexPath.row == 2) {
            if (self.sendFee < 0) {
                [self getSendFeeFromServer];
            }
            else{
                [self showSendCoinView];
            }
        }
        else if (indexPath.row == 3) {
            MHHistoryListViewController* vc = [[MHHistoryListViewController alloc] initWithNibName:@"MHHistoryListViewController" bundle:nil];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else if (indexPath.section == 3) {
        if (indexPath.row == 1) {
            MHChangePassViewController* vc = [[MHChangePassViewController alloc] initWithNibName:@"MHChangePassViewController" bundle:nil];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (void)leftButtonPressed: (id)sender {
    [[MHAppDelegate sharedApp].viewController showLeftPanelAnimated:YES];
}

//- (void)rightButton

- (IBAction)logoutPressed:(id)sender {
    [Lib setUserLogin:NO];
    [[MHAppDelegate sharedApp].viewController showHomeVc];
    [[MHAppDelegate sharedApp].viewController updateUserInfo];
}

- (void)setCardIndex:(NSInteger)cardIndex {
    _cardIndex = cardIndex;
    self.cardType.text = [self.cardData[_cardIndex] objectForKey:kCardName];
}

- (IBAction)addCoinOk:(id)sender {
    NSString* cardNumber = self.cardNumber.text;
    NSString* cardSerial = self.cardSerial.text;
    NSString* email = [Lib stringForKey:@"Email"];
    if (!cardNumber || cardNumber.length == 0) {
        [Lib showMessage:@"Bạn chưa nhập mã thẻ" title:@""];
        return;
    }
    if (!cardSerial || cardSerial.length == 0) {
        [Lib showMessage:@"Bạn chưa nhập mã số serial" title:@""];
        return;
    }
    NSDictionary* dict = self.cardData[_cardIndex];
    NSString* cardType = dict[kCardId];
    NSString* token = [Lib md5:[NSString stringWithFormat:@"%@%@%@%@%@%@", cardType, cardNumber, cardSerial, email, kServiceId, kServiceToken]];
    
    NSString* url = [NSString stringWithFormat:@"http://paygate.mho.vn/Recharge/Card?typecard=%@&codecard=%@&serialcard=%@&userId=%@&serviced=%@&token=%@", cardType, cardNumber, cardSerial, email, kServiceId, token];
    [Lib showLoadingView];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString* ret = [ServiceLib sendGetRequest:url useCache:NO];
        if (ret) {
            SBJsonParser* parser = [[SBJsonParser alloc] init];
            id dict = [parser objectWithString:ret];
            NSString* message = dict[@"Message"];
            BOOL isSuccess = [dict[@"IsSuccess"] boolValue];
            dispatch_async(dispatch_get_main_queue(), ^{
                [Lib removeLoadingView];
                if (isSuccess) {
                    [self reloadData];
                }
                [Lib showMessage:message title:@""];
            });
        }
    });
}

- (IBAction)addCoinCancel:(id)sender {
    [self.addCoinView removeFromSuperview];
}

- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
}

- (void)keyboardWasShown: (NSNotification*)noti {
    NSDictionary* info = [noti userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    keyboardSize = kbSize;
}

- (void)keyboardWillBeHidden: (NSNotification*)noti {

}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField == self.cardType) {
        [self showCardTypeActionSheet];
        return NO;
    }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (textField == self.cardSerial) {
        CGRect frame = self.addCoinView.frame;
        float offset = self.view.frame.size.height - frame.size.height - frame.origin.y - keyboardSize.height;
        if (offset < 0) {
            frame.origin.y += offset;
            [UIView animateWithDuration:0.2 animations:^{
                self.addCoinView.frame = frame;
            }];
        }
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (self.addCoinView.superview) {
        CGRect frame1 = self.view.frame;
        CGRect frame2 = self.addCoinView.frame;
        CGRect frame = CGRectMake((frame1.size.width - frame2.size.width) / 2, (frame1.size.height - frame2.size.height) / 2, frame2.size.width, frame2.size.height);
        [UIView animateWithDuration:0.2 animations:^{
            self.addCoinView.frame = frame;
        }];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.sendMoney) {
        NSString* nString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if (nString.length > [NSString stringWithFormat:@"%ld", LONG_MAX].length) {
            return NO;
        }
        self.sendMoney.text = nString;
        [self updateSendTotalMoney];
        return NO;
    }
    return YES;
}

- (void)showCardTypeActionSheet {
    if (self.cardActionSheet == nil) {
        NSMutableArray* data = [NSMutableArray array];
        for (id dict in self.cardData) {
            [data addObject:dict[kCardName]];
        }
        self.cardActionSheet = [[ActionSheetStringPicker alloc] initWithTitle:@"Chọn loại thẻ" rows:data initialSelection:0 doneBlock:^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
            self.cardIndex = selectedIndex;
        } cancelBlock:^(ActionSheetStringPicker *picker) {
            
        } origin:self.view];
    }
    [self.cardActionSheet showActionSheetPicker];
}

- (IBAction)sendCoinOK:(id)sender {
    NSString* email = self.receiveEmail.text;
    NSString* moneyText = self.sendMoney.text;
    if (!email || email.length == 0) {
        [Lib showMessage:@"Bạn chưa nhập tài khoản người người nhận!" title:@""];
        return;
    }
    
    if (!moneyText || moneyText.length == 0) {
        [Lib showMessage:@"Bạn chưa nhập số tiền cần chuyển" title:@""];
        return;
    }
    

    long long total = [self updateSendTotalMoney];
    long long money = [moneyText integerValue];
    [UIAlertView showWithTitle:@"Xác nhận" message:[NSString stringWithFormat:@"Chuyển tiền tới tài khoản %@. Tổng số tiền giao dịch là %lld. Bạn có muốn tiếp tục không?", email, total] cancelButtonTitle:@"Huỷ" otherButtonTitles:@[@"Đồng ý"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 1) {
            [self acceptSendingCoin:email coin:money];
        }
    }];
}

- (IBAction)sendCoinCancel:(id)sender {
    [self.sendCoinView removeFromSuperview];
}

- (void)acceptSendingCoin: (NSString*)email coin: (long long)coin {
    NSString* user = [Lib stringForKey:@"Email"];
    NSString* pass = [Lib stringForKey:@"paccount"];
    NSString* token = [Lib md5:[NSString stringWithFormat:@"%@%@%@%lld%@%@", user, pass, email, coin, kServiceId, kServiceToken]];
    NSString* url = [NSString stringWithFormat:@"http://paygate.mho.vn/Transfer/MHOTransferGoldToUser?fromUserId=%@&password=%@&toUserIdOrEmail=%@&goldTransfer=%lld&serviceId=%@&token=%@", user, pass, email, coin, kServiceId, token];
    [Lib showLoadingView];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString* ret = [ServiceLib sendGetRequest:url useCache:NO];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [Lib removeLoadingView];
            if (ret) {
                SBJsonParser* parser = [[SBJsonParser alloc] init];
                id dict = [parser objectWithString:ret];
                NSString* message = dict[@"Message"];
                BOOL isSuccess = [dict[@"IsSuccess"] boolValue];
                if (isSuccess) {
                    [self reloadData];
                }
                [Lib showMessage:message title:@""];
            }
        });
    });
}

- (void)getSendFeeFromServer {
    [Lib showLoadingView];
    NSString* token = [Lib md5:[NSString stringWithFormat:@"%@%@", kServiceId, kServiceToken]];
    NSString* url = [NSString stringWithFormat:@"http://paygate.mho.vn/Transfer/GetFeeTransferToOther?serviceId=%@&token=%@", kServiceId, token];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString* ret = [ServiceLib sendGetRequest:url useCache:NO];
        NSLog(@"get send free: %@", ret);
        dispatch_async(dispatch_get_main_queue(), ^{
            [Lib removeLoadingView];
            if (ret) {
                self.sendFee = [ret intValue];
                [self updateSendTotalMoney];
                [self showSendCoinView];
            }
            else {
            
            }
        });
    });
}

- (long long)updateSendTotalMoney {
    NSString* money = self.sendMoney.text;
    if (money) {
        long long value = [money integerValue];
        float fee = 0;
        if (self.sendFee >= 0) {
            fee = self.sendFee;
        }
        long long nValue = value + floor((float)value * (fee / 100.0f));
//        NSLog(@"total money: %ld", (long)nValue);
        self.sendTotalMoney.text = [NSString stringWithFormat:@"%lld", nValue];
        return nValue;
    }
    return 0;
}

- (void)showSendCoinView {
    CGRect frame1 = self.view.frame;
    CGRect frame2 = self.addCoinView.frame;
    CGRect frame = CGRectMake((frame1.size.width - frame2.size.width) / 2, (frame1.size.height - frame2.size.height) / 2, frame2.size.width, frame2.size.height);
    self.sendCoinView.frame = frame;
    [self.view addSubview:self.sendCoinView];
}

@end
